<template>
    <div class="tab">
        <span>{{length}} items left</span>
        <ul class="tab__btn">
            <li v-for="(item ,index) of tabs" :key="index"
                @click="changeStatus(index)"
                :class="{active: item.isActive}">{{item.func}}</li>
        </ul>
        <span class="clearAll" @click="clearAll">Clear All</span>
    </div>
</template>

<script>
    import bus from '../asset/eventBus.js'
    export default {
        name: "tab",
        props: {
            length: {
                type: Number,
                required: true
            }
        },
        data() {
            return {
                tabs : [
                    {func:'all',isActive: true},
                    {func:'active',isActive: false},
                    {func:'completed',isActive: false}
                ]
            }
        },
        methods: {
            changeStatus: function (index) {
                const tab = this.tabs,
                    len = this.tabs.length,
                    flag = tab[index].isActive;
                tab[index].isActive = flag === false ? !flag : true;
                bus.$emit('status', tab[index].func);
                for(let i = 0;i < len;i++) {
                    if(i !== index) {
                        tab[i].isActive = false
                    }
                }
            },
            clearAll: function() {
                const tab = this.tabs;
                const obj = tab.filter(item => item.isActive === true);
                const func = obj[0].func;
                this.$emit('clearAll',func)
            }
        },
        created: function() {
            const that = this;
            const tab = that.tabs,
                len = that.tabs.length;
            bus.$on('refreshPage',function() {
                let flag = tab.findIndex(item => item.isActive === true);
                that.changeStatus(flag)
            })
        }
    }
</script>

<style scoped lang="scss">
    .tab {
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 100%;
        height: 58px;
        padding: 20px;
        background: #fff;
        color: #a7a7a7;
        .tab__btn {
            li {
                display: inline-block;
                padding: 0 10px;
                height: 40px;
                line-height: 40px;
                cursor: pointer;
            }
            li.active {
                border: 1px solid;
                border-radius: 4px;
                color:  #95251a;
            }
        }
        .clearAll {
            cursor: pointer;
        }
        .clearAll:hover {
            color: #95251a;
            font-weight: 300;
        }
    }
</style>